package com.sinosoft.web.common.tag;

import cn.com.sinux.spring.commons.SpringUtils;
import com.sinosoft.hydra.um.domain.model.Site;
import com.sinosoft.hydra.um.helper.AuthContextHelper;
import com.sinosoft.hydra.um.services.SysResourceService;
import org.apache.commons.lang.StringUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2016/6/14.
 */
public class SiteMapTag extends javax.servlet.jsp.tagext.TagSupport {

    private String url;
    private String params;


    public int doStartTag() throws JspException {
        try {
            JspWriter out = this.pageContext.getOut();
            List<Site> sites = new ArrayList<Site>();
            sites.add(new Site("首页", pageContext.getServletContext().getContextPath() + "/app/api/home/index"));
            SysResourceService sysResourceService = SpringUtils.getBean(SysResourceService.class);
            sites.addAll(sysResourceService.getSites(url, params, AuthContextHelper.getLoginUser().getSysResources()));
            List<String> results = new LinkedList<String>();
            for (Site site : sites) {
                String link = site.getLink();
                if(StringUtils.isNotBlank(link)){
                    link = link.startsWith(pageContext.getServletContext().getContextPath()) ? link : (pageContext.getServletContext().getContextPath() + site.getLink());
                }else{
                    link = "javascript:void(0)";
                }
                results.add("<a href=\"" + link + "\" " +
                        (StringUtils.isBlank(site.getId()) ? "" : "data-id=\"" + site.getId() + "\"") + ">" + site.getName() + "</a>");
            }
            out.println(StringUtils.join(results, "<i class=\"fa fa-angle-right mlr5\"></i>"));
        } catch (Exception e) {
            throw new JspException(e.getMessage());
        }
        return SKIP_BODY;
    }


    public int doEndTag() throws JspException {
        return EVAL_PAGE;
    }


    public void release() {
        super.release();
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getParams() {
        return params;
    }

    public void setParams(String params) {
        this.params = params;
    }
}
